<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/8
 * Time: 11:37
 */

namespace common\business\emppos;


use common\models\EmployeePosition;
use common\models\kingdee\PersonPosition;
use common\result\ActionResult;
use yii\db\Query;

class EmployeePositionService
{
    /**
     * @param callback|null $writeBackHandler
     * @return \common\result\ActionResult
     */
    public function sync($writeBackHandler = null){
        $totalCount = PersonPosition::find()->count();

        $totalResult = new ActionResult();

        $db = PersonPosition::getDb();
        $query = (new Query())->from('T_HR_PERSONPOSITION THPP')
            ->leftJoin('T_ORG_POSITION TOP', 'TOP.FID = THPP.FPRIMARYPOSITIONID')
            ->leftJoin('T_BD_PERSON TBP', 'TBP.FID = THPP.FPERSONID')
            ->select([
                'employee_name' => 'TBP.FNAME_L2',
                'employee_number' => 'TBP.FNUMBER',
                'position_name' => 'TOP.FNAME_L2',
                'position_number' => 'TOP.FNUMBER',
            ])
            ->orderBy([
                'THPP.FID' => SORT_ASC,
            ]);

        $offset = 0;
        $pageSize = 100;
        $count = $pageSize;

        while ($count >= $pageSize) {
            $all = $query->offset($offset)->limit($pageSize)->all($db);
            $count = count($all);
            $offset += $pageSize;
            foreach ($all as $item){
                $newEmployeePosition = new EmployeePosition();
                $newEmployeePosition->setAttributes($item);

                $employeePositionInDb = EmployeePosition::findOne([
                    'employee_number' => $newEmployeePosition->employee_number,
                    'position_number' => $newEmployeePosition->position_number,
                ]);

                $api = new EmployeePositionApiHandler();
                if (!$employeePositionInDb){
                    $totalResult->addSubResult($api->createEmployeePosition($newEmployeePosition));
                }
                else {
                    $totalResult->addSubResult($api->updateEmployeePosition($newEmployeePosition, $employeePositionInDb));
                }
                if ($writeBackHandler){
                    $paramArr = [
                        'totalCount' => $totalCount,
                        'finishCount' => $totalResult->total_count,
                        'message' => $totalResult->message,
                    ];
                    call_user_func_array($writeBackHandler, $paramArr);
                }
            }
        }
        return $totalResult;
    }
}